<template>
  <div class="matching-history-container">
    <div class="page-header">
      <div class="page-title">匹配历史记录</div>
      <div class="page-actions">
        <el-button icon="Download" @click="handleExportHistory">导出记录</el-button>
        <el-button type="primary" icon="Refresh" @click="refreshData">刷新</el-button>
      </div>
    </div>

    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="资产">
          <el-select 
            v-model="searchForm.assetId" 
            placeholder="选择资产"
            clearable
            style="width: 220px">
            <el-option 
              v-for="item in assetOptions" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id">
              <span>{{ item.name }}</span>
              <span style="color: var(--text-color-secondary); margin-left: 10px">{{ item.ip }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="匹配方式">
          <el-select 
            v-model="searchForm.matchType" 
            placeholder="选择匹配方式"
            clearable
            style="width: 150px">
            <el-option label="自动匹配" value="auto" />
            <el-option label="手动匹配" value="manual" />
          </el-select>
        </el-form-item>
        <el-form-item label="匹配日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 260px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计信息卡片 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stats-card" shadow="hover">
            <div class="stats-icon total-icon">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-title">总匹配记录</div>
              <div class="stats-value">{{ statistics.total }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card" shadow="hover">
            <div class="stats-icon auto-icon">
              <el-icon><Connection /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-title">自动匹配</div>
              <div class="stats-value">{{ statistics.auto }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card" shadow="hover">
            <div class="stats-icon manual-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-title">手动匹配</div>
              <div class="stats-value">{{ statistics.manual }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card" shadow="hover">
            <div class="stats-icon verified-icon">
              <el-icon><Check /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-title">已验证</div>
              <div class="stats-value">{{ statistics.verified }}</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 匹配历史表格 -->
    <div class="history-table-container">
      <el-table 
        :data="matchingHistory" 
        border 
        style="width: 100%"
        v-loading="tableLoading">
        <el-table-column prop="id" label="匹配ID" width="100" />
        <el-table-column label="漏洞信息" min-width="200">
          <template #default="{ row }">
            <div class="vuln-info">
              <div class="vuln-id">{{ row.vulnerability.id }}</div>
              <div class="vuln-name">{{ row.vulnerability.name }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="资产信息" min-width="200">
          <template #default="{ row }">
            <div class="asset-info">
              <div class="asset-name">{{ row.asset.name }}</div>
              <div class="asset-ip">{{ row.asset.ip }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="matchType" label="匹配方式" width="100">
          <template #default="{ row }">
            <el-tag :type="row.matchType === 'auto' ? 'info' : 'success'" size="small">
              {{ row.matchType === 'auto' ? '自动' : '手动' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="危害等级" width="90">
          <template #default="{ row }">
            <el-tag :type="getTagType(row.vulnerability.level)" size="small">
              {{ formatLevel(row.vulnerability.level) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="matchTime" label="匹配时间" width="150" />
        <el-table-column label="匹配分值" width="110">
          <template #default="{ row }">
            <el-progress 
              :percentage="row.confidence" 
              :color="getConfidenceColor(row.confidence)" 
              :stroke-width="8" />
          </template>
        </el-table-column>
        <el-table-column label="验证状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getVerificationTagType(row.verificationStatus)" size="small">
              {{ formatVerificationStatus(row.verificationStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button type="primary" link icon="View" @click="handleViewDetail(row)">查看详情</el-button>
            <el-button 
              v-if="row.verificationStatus === 'pending'" 
              type="success" 
              link 
              icon="Check" 
              @click="handleVerify(row)">验证</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Document, Connection, User, Check } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

// 路由
const router = useRouter()

// 表格加载状态
const tableLoading = ref(false)

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  assetId: '',
  matchType: '',
  dateRange: ''
})

// 资产选项
const assetOptions = ref([
  { id: '1', name: '内部Web服务器', ip: '192.168.1.100' },
  { id: '2', name: '数据库服务器', ip: '192.168.1.101' },
  { id: '3', name: '文件服务器', ip: '192.168.1.102' },
  { id: '4', name: '测试服务器', ip: '192.168.2.100' },
  { id: '5', name: '生产环境服务器', ip: '10.10.10.50' }
])

// 统计信息
const statistics = reactive({
  total: 0,
  auto: 0,
  manual: 0,
  verified: 0
})

// 匹配历史数据
const matchingHistory = ref([])

// 格式化危害等级
const formatLevel = (level) => {
  const levelMap = {
    'critical': '严重',
    'high': '高危',
    'medium': '中危',
    'low': '低危'
  }
  return levelMap[level] || level
}

// 获取标签类型
const getTagType = (level) => {
  const typeMap = {
    'critical': 'danger',
    'high': 'warning',
    'medium': '',
    'low': 'info'
  }
  return typeMap[level] || ''
}

// 获取验证状态标签类型
const getVerificationTagType = (status) => {
  const typeMap = {
    'pending': 'info',
    'in_progress': 'warning',
    'verified': 'success'
  }
  return typeMap[status] || ''
}

// 格式化验证状态
const formatVerificationStatus = (status) => {
  const statusMap = {
    'pending': '待验证',
    'in_progress': '验证中',
    'verified': '已验证'
  }
  return statusMap[status] || status
}

// 获取匹配分值颜色
const getConfidenceColor = (confidence) => {
  if (confidence >= 80) return '#67C23A'
  if (confidence >= 50) return '#E6A23C'
  return '#F56C6C'
}

// 处理分页变化
const handleSizeChange = (val) => {
  pageSize.value = val
  loadMatchingHistory()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadMatchingHistory()
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadMatchingHistory()
}

// 重置搜索
const resetSearch = () => {
  searchForm.assetId = ''
  searchForm.matchType = ''
  searchForm.dateRange = ''
  handleSearch()
}

// 刷新数据
const refreshData = () => {
  loadMatchingHistory()
  loadStatistics()
}

// 加载统计信息
const loadStatistics = () => {
  // 模拟API调用
  setTimeout(() => {
    statistics.total = 68
    statistics.auto = 42
    statistics.manual = 26
    statistics.verified = 31
  }, 300)
}

// 加载匹配历史数据
const loadMatchingHistory = () => {
  tableLoading.value = true
  
  // 模拟API调用
  setTimeout(() => {
    const mockData = []
    
    // 模拟各种状态的匹配历史数据
    for (let i = 1; i <= 100; i++) {
      const isAuto = Math.random() > 0.4
      const verificationStatus = ['pending', 'in_progress', 'verified'][Math.floor(Math.random() * 3)]
      const level = ['critical', 'high', 'medium', 'low'][Math.floor(Math.random() * 4)]
      const year = 2023
      const month = Math.floor(Math.random() * 12) + 1
      const day = Math.floor(Math.random() * 28) + 1
      const hour = Math.floor(Math.random() * 24)
      const minute = Math.floor(Math.random() * 60)
      
      mockData.push({
        id: `MATCH-${10000 + i}`,
        vulnerability: {
          id: `VLN-${2023000 + i % 50}`,
          name: `示例漏洞-${i % 50 + 1}`,
          level
        },
        asset: {
          id: `${(i % 5) + 1}`,
          name: assetOptions.value[i % 5].name,
          ip: assetOptions.value[i % 5].ip
        },
        matchType: isAuto ? 'auto' : 'manual',
        matchTime: `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}:00`,
        confidence: Math.floor(Math.random() * 60) + 40, // 40-100之间的随机值
        verificationStatus
      })
    }
    
    // 过滤逻辑
    let filteredData = [...mockData]
    
    if (searchForm.assetId) {
      filteredData = filteredData.filter(item => 
        item.asset.id === searchForm.assetId
      )
    }
    
    if (searchForm.matchType) {
      filteredData = filteredData.filter(item => 
        item.matchType === searchForm.matchType
      )
    }
    
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      const startDate = new Date(searchForm.dateRange[0])
      const endDate = new Date(searchForm.dateRange[1])
      
      filteredData = filteredData.filter(item => {
        const matchDate = new Date(item.matchTime)
        return matchDate >= startDate && matchDate <= endDate
      })
    }
    
    total.value = filteredData.length
    
    // 分页
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    matchingHistory.value = filteredData.slice(start, end)
    
    tableLoading.value = false
  }, 500)
}

// 查看详情
const handleViewDetail = (row) => {
  console.log('查看匹配详情:', row.id)
  router.push(`/matching/detail/${row.id}`)
}

// 验证漏洞
const handleVerify = (row) => {
  console.log('验证漏洞:', row.id)
  ElMessage.success(`已将匹配 ${row.id} 加入验证队列`)
  row.verificationStatus = 'in_progress'
}

// 导出历史
const handleExportHistory = () => {
  console.log('导出匹配历史')
  ElMessage.success('匹配历史记录导出成功')
}

// 初始化
onMounted(() => {
  loadMatchingHistory()
  loadStatistics()
})
</script>

<style lang="scss" scoped>
.matching-history-container {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .page-title {
      font-size: 20px;
      font-weight: bold;
      color: var(--text-color);
    }
    
    .page-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .stats-section {
    margin-bottom: 20px;
    
    .stats-card {
      display: flex;
      align-items: center;
      padding: 15px;
      
      .stats-icon {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 48px;
        height: 48px;
        border-radius: 12px;
        margin-right: 15px;
        font-size: 24px;
        
        &.total-icon {
          background-color: rgba(64, 158, 255, 0.1);
          color: #409EFF;
        }
        
        &.auto-icon {
          background-color: rgba(103, 194, 58, 0.1);
          color: #67C23A;
        }
        
        &.manual-icon {
          background-color: rgba(230, 162, 60, 0.1);
          color: #E6A23C;
        }
        
        &.verified-icon {
          background-color: rgba(144, 147, 153, 0.1);
          color: #909399;
        }
      }
      
      .stats-info {
        .stats-title {
          font-size: 14px;
          color: var(--text-color-secondary);
          margin-bottom: 5px;
        }
        
        .stats-value {
          font-size: 24px;
          font-weight: bold;
          color: var(--text-color);
        }
      }
    }
  }
  
  .history-table-container {
    .vuln-info, .asset-info {
      display: flex;
      flex-direction: column;
      
      .vuln-id, .asset-name {
        font-weight: bold;
      }
      
      .vuln-name, .asset-ip {
        font-size: 13px;
        color: var(--text-color-secondary);
        margin-top: 3px;
      }
    }
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style> 